<script setup>
import { ref } from 'vue';
import InputText from 'primevue/inputtext';
import Dialog from 'primevue/dialog';
import FileUpload from 'primevue/fileupload';
import Button from 'primevue/button';
import { useToast } from 'primevue/usetoast';
import axios from 'axios';
import { useAdminStore } from '@/store/admin';

const adminStore = useAdminStore();
const toast = useToast();

// 数据状态
const dialogVisible = ref(false); // 对话框显示状态
const imageUrl = ref(''); // 图片 URL
const previewImage = ref(''); // 预览图
const selectedFile = ref(null); // 选中的文件

// 打开对话框
const openDialog = () => {
    dialogVisible.value = true;
};

// 选择图片
const onSelectImage = ({ files }) => {
    const file = files[0];
    if (!file) return;

    // 生成预览图
    const reader = new FileReader();
    reader.onload = (e) => {
        previewImage.value = e.target.result;
    };
    reader.readAsDataURL(file);

    selectedFile.value = file;
};

// 上传图片
const uploadImage = async () => {
    if (!selectedFile.value) return;

    const formData = new FormData();
    formData.append('file', selectedFile.value);

    try {
        const config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        };

        // 添加鉴权令牌
        if (adminStore.token) {
            config.headers.Authorization = `Bearer ${adminStore.token}`;
        }
        const response = await axios.post('/api/v1/backend/upload/picture', formData, config);
        // console.log(response);
        // 更新图片 URL
        imageUrl.value = response.data.data.url;

        toast.add({
            severity: 'success',
            summary: '上传成功',
            detail: '图片已上传',
            life: 3000
        });

        // 关闭对话框
        dialogVisible.value = false;
    } catch (error) {
        toast.add({
            severity: 'error',
            summary: '上传失败',
            detail: error.message,
            life: 3000
        });
    }
};

// 错误处理
const onUploadError = (error) => {
    let message = '文件上传错误';
    if (error.message.includes('maxFileSize')) {
        message = '文件大小不能超过1MB';
    } else if (error.message.includes('accept')) {
        message = '仅支持图片格式';
    }
    toast.add({
        severity: 'error',
        summary: '错误',
        detail: message,
        life: 3000
    });
};
</script>

<template>
    <div>
        <!-- 输入框 -->
        <div class="field">
            <label for="imageUrl">图片地址</label>
            <InputText id="imageUrl" v-model="imageUrl" placeholder="点击选择图片" readonly @click="openDialog" />
        </div>

        <!-- 图片上传对话框 -->
        <Dialog v-model:visible="dialogVisible" header="上传图片" :modal="true" :style="{ width: '500px' }">
            <!-- 图片预览 -->
            <div v-if="previewImage" class="preview-container">
                <img :src="previewImage" alt="预览图片" class="preview-image" />
            </div>

            <!-- 文件选择 -->
            <FileUpload mode="basic" name="image" :auto="true" :customUpload="true" :multiple="false" :maxFileSize="1024000" accept="image/*" chooseLabel="选择图片" @select="onSelectImage" @error="onUploadError" />

            <!-- 上传按钮 -->
            <div class="flex justify-content-end mt-3">
                <Button label="上传" icon="pi pi-upload" class="p-button-primary" :disabled="!selectedFile" @click="uploadImage" />
            </div>
        </Dialog>
    </div>
</template>

<style scoped>
.preview-container {
    text-align: center;
    margin-bottom: 1rem;
}

.preview-image {
    max-width: 100%;
    max-height: 200px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.field {
    margin-bottom: 1rem;
}
</style>
